#!/usr/bin/python2.6
# -*- coding:utf-8 -*-

from __future__ import with_statement

import os
import traceback
import urllib

from django.http import HttpResponseRedirect
from django.http import Http404
from django.template import RequestContext 
from django.shortcuts import render_to_response 
from django.utils.encoding import smart_str

from ubbparser import compiler

PAGE_DIR = os.path.abspath('pages_html')
HELLO_WORD = 'Hello,World!'

def get_page(path,suffix):
    return os.path.normpath(os.path.join(PAGE_DIR,path)) + suffix

def get_html(path):
    return get_page(path,'.html')

def get_ubb(path):
    return get_page(path,'.ubb')

def create_dir(path):
    plist = path.split('/')
    plist.insert(0,PAGE_DIR)
    fpath = '/'.join(plist[:-1])
    if not os.path.exists(fpath):
        os.makedirs(fpath)

def check_path(path):
    if '.' in path:
        return False
    return True

def index(request):
    return HttpResponseRedirect('/index')

def browse(request,path):
    if request.method != 'GET':
        return HttpResponseRedirect('/index')
    print path
    if not check_path(path):
        raise Http404
    fpath = get_html(path)
    if not os.path.exists(fpath):
        content = HELLO_WORD
    else:
        try:
            with open(fpath) as f:
                content = f.read()
        except IOError:
            traceback.print_exc()
            raise Http404
    context = RequestContext(request,{'content':content,'path':path})
    return render_to_response('reader.html',context)

def edit(request,path):
    if request.method != 'GET':
        return HttpResponseRedirect('/index')
    if not check_path(path):
        raise Http404
    fpath = get_ubb(path)
    if not os.path.exists(fpath):
        content = HELLO_WORD
    else:
        try:
            with open(fpath) as f:
                content = f.read()
        except IOError:
            raise Http404
    context = RequestContext(request,{'content':content,'path':path})
    return render_to_response('editor.html',context)

def commit(request,path):
    if request.method != 'POST':
        return HttpResponseRedirect('/')
    if not check_path(path):
        raise Http404
    content = request.POST.get('content','')
    if content:
        content = smart_str(content)
    fpath = get_ubb(path)
    try:
        create_dir(path)
        with open(fpath,'w') as f:
            f.write(content)
      #  c = compiler(content)
      #  print c.tree
      #  print c.part
      #  print c.left
      #  html = c.ubbtohtml().encode('utf-8')
        html = content
        fpath = get_html(path)
        with open(fpath,'w') as f:
            f.write(html)
    except IOError:
        traceback.print_exc()
        raise Http404
    return HttpResponseRedirect('/' + path)

import unittest

class UbbTest(unittest.TestCase):

    def test_gethtml(self):
        self.assertEqual(get_html('index'),'%s/index.html' % PAGE_DIR)
        self.assertEqual(get_html('test/index'),'%s/test/index.html' % PAGE_DIR)

    def test_getubb(self):
        self.assertEqual(get_ubb('index'),'%s/index.ubb' % PAGE_DIR)
        self.assertEqual(get_ubb('test/index'),'%s/test/index.ubb' % PAGE_DIR)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(UbbTest)
    unittest.TextTestRunner().run(suite)
